<template>
  <div style="border: 1px solid #ccc; border-radius: 10px; overflow: hidden">
    <Toolbar
      style="border-bottom: 1px solid #ccc;"
      :editor="editor"
      :default-config="toolbarConfig"
      mode="simple"
    />

    <Editor
      style="min-height: 200px; overflow-y: hidden;"
      v-model="defaultValue"
      :default-config="editorConfig"
      mode="simple"
      @onCreated="onCreated"
      @onChange="handleChange"
    />
  </div>
</template>

<script>
import Vue from 'vue'
import {Editor, Toolbar} from '@wangeditor/editor-for-vue'

export default Vue.extend({
  name: 'editor',
  components: {Editor, Toolbar},
  props: {
    value: {
      type: String,
      default: ""
    },
    readMode: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      defaultValue: "",
      editor: null,
      toolbarConfig: {
        excludeKeys: [
          'fullScreen', 'group-more-style', 'color', 'bgColor', 'codeBlock', 'insertLink', 'insertVideo', 'insertImage', 'redo', 'undo', 'insertTable', 'todo'
        ]
      },
      editorConfig: {
        autoFocus: false,
        readOnly: this.readMode,
        placeholder: "请输入内容……",
        MENU_CONF: {
          uploadImage: {
            server: '/upload/image',
            fieldName: 'file',
            maxFileSize: 5 * 1024 * 1024
          },
        }
      }
    }
  },
  created() {
    setTimeout(() => {
      this.defaultValue = this.value
    }, 600)
  },
  methods: {
    onCreated(editor) {
      this.editor = Object.seal(editor)
    },
    handleChange(e) {
      let html = e.getHtml()
      if (html === '<p><br></p>'){
        html = null
      }
      this.$emit('update:input', html)
    }
  },
  beforeDestroy() {
    const editor = this.editor
    if (editor === null) return null
    editor.destroy()
  }
})
</script>

<style src="@wangeditor/editor/dist/css/style.css"></style>
